<?php
/**
 * This file is part of the Zhan Framework (http://zhan.com)
 * Copyright © 2015 Zhan, Inc. (http://zhan.com)
 */

namespace Zhan\Exception;

use Zhan\Container\ServiceProvider;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PlainTextHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;

class ExceptionServiceProvider extends ServiceProvider {

    /**
     * 注册服务至Application
     *
     * @return mixed
     */
    public function register()
    {
        $this->registerWhoops();
        $this->app['exception']->register();
    }

    public function registerWhoops()
    {
        $this->registerWhoopsHandler();
        $this->app['exception'] = function($app) {
            $whoops = new Run();
            $whoops->writeToOutput($app['debug']);
            return $whoops->pushHandler($app['exception.handler']);
        };
    }

    public function registerWhoopsHandler()
    {
        $this->app['exception.handler'] = function() {
            if(PHP_SAPI == 'cli') {
                return new PlainTextHandler();
            } else if($this->requestWantsAjax()) {
                return new JsonResponseHandler();
            } else {
                return new PrettyPageHandler();
            }
        };
    }

    /**
     * 判断是否ajax或返回json
     * @return bool
     */
    protected function requestWantsAjax()
    {
        $acceptable = $this->app['request']->getAcceptableContentTypes();
        $wantsJson = isset($acceptable[0]) && $acceptable[0] == 'application/json';
        return $this->app['request']->isXmlHttpRequest() || $wantsJson;
    }
}